package com.project.web.wechat.controller.app.cpWeChat;

import com.project.common.core.utils.exception.Result;
import com.project.web.config.WxCorp.WxCpConfig;
import com.project.web.config.WxCorp.WxCpConfiguration;
import com.project.web.util.exception.WeChatCustomException;
import com.project.web.wechat.controller.common.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.cp.api.WxCpMessageService;
import me.chanjar.weixin.cp.bean.message.WxCpLinkedCorpMessage;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import me.chanjar.weixin.cp.bean.message.WxCpMessageSendResult;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 消息推送接口
 *
 * @author wyy
 * @date 2020-06-24
 */
@Api(tags = "消息推送接口")
@RestController("workWxMsgController")
@RequestMapping("/weChat/auth/workWx/msg")
public class WorkWxMsgController extends BaseController {

    /**
     * 发送应用消息
     *
     * @param wxCpMessage
     * @param request     请求对象
     * @return
     */
    @ApiOperation("发送应用消息")
    @PostMapping(value = "/send")
    public Result<WxCpMessageSendResult> text(@RequestBody WxCpMessage wxCpMessage, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpMessageService messageService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId()).getMessageService();

        try {
            WxCpMessageSendResult wxCpMessageSendResult = messageService.send(wxCpMessage);
            return getResult(wxCpMessageSendResult);
        } catch (Exception e) {
            log.error("发送文本消息出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getMessage()), e.getMessage());
        }
    }

    /**
     * 发送应用图片消息
     *
     * @return
     */
    @ApiOperation("发送企业互联消息")
    @PostMapping(value = "/sendLinkedCorpMessage")
    public Result<WxCpMessageSendResult> img(@RequestBody WxCpLinkedCorpMessage wxCpMessage, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpMessageService messageService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId()).getMessageService();

        try {
            WxCpMessageSendResult wxCpMessageSendResult = messageService.sendLinkedCorpMessage(wxCpMessage);
            return getResult(wxCpMessageSendResult);
        } catch (Exception e) {
            log.error("发送文本消息出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getMessage()), e.getMessage());
        }
    }
}
